package com.palmelf.util;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

/**
 * 用于跟随系统启动的线程<br>
 * Servlet implementation class StartLoad
 */
public class StartLoad extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static Logger LOG = Logger.getLogger("StartLoad");
	BaseMonitorThread mt = null;;
	String monitorPath = "D:\\data";
	String targetPath = "";

	@Override
	public void init() throws ServletException {
		if (targetPath == null || targetPath.length() < 2) {
			String realpath = this.getServletConfig().getServletContext().getRealPath("/");
			targetPath = realpath + "\\images";
			File imageFolder = new File(this.targetPath);
			if (!imageFolder.exists()) {
				imageFolder.mkdirs();
			}
		}
		LOG.debug("servlet被实例化,文件将会拷贝到" + targetPath);
		String appPath = this.getServletConfig().getServletContext().getRealPath("/");
		LOG.debug("使用监控上传的图片来显示监控画面");
		mt = new ImgMonitorThread();
		mt.stop = false;
		List<String> fileType = new ArrayList<String>();
		fileType.add("jpg");
		fileType.add("bmp");
		fileType.add("png");
		mt.setFileType(fileType);
		// 设置被监控目录
		mt.setMonitorPath(monitorPath);
		// 发现新文件后,指定拷贝到的目录
		mt.setAppPath(appPath);
		mt.setTargetPath(targetPath);
		mt.start();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,
			IOException {
		this.doGet(request, response);
	}

	public void destroy() {
		mt.stop = true; // 设置共享变量为true
		mt.interrupt(); // 阻塞时退出阻塞状态
		if (mt.isAlive()) {
			LOG.debug("监控图片线程已经安全退出");
		} else {
			LOG.error("监控图片线程尚未安全退出,这样可能导致内存泄露");
		}
	}
}
